<template>
	<view>
		<view>
			<table-title content="水电表详细管理"></table-title>

			<!-- <small-title content="当前房间水电表信息"></small-title> -->
			<view style="margin-left: 50rpx;margin-right: 50rpx;">
				<uni-forms :modelValue="orderInfo">
					<uni-forms-item label="楼盘" name="build">
						<uni-easyinput :disabled="true" name="build" style="background-color: #ffffff;" type="text" v-model="orderInfo.build" />
					</uni-forms-item>
					<uni-forms-item label="楼层" name="floor">
						<uni-easyinput :disabled="true" name="floor" style="background-color: #ffffff;" type="text" v-model="orderInfo.floor" />
					</uni-forms-item>
					<uni-forms-item label="单元" name="unit">
						<uni-easyinput :disabled="true" name="unit" style="background-color: #ffffff;" type="text" v-model="orderInfo.unit" />
					</uni-forms-item>
					<uni-forms-item label="上月电表读数" name="prevElectricity">
						<uni-easyinput name="prevElectricity" style="background-color: #ffffff;" type="number" v-model="orderInfo.prevElectricity" disabled/>
					</uni-forms-item>
					<uni-forms-item label="上月电费" name="prevElectricityBill">
						<uni-easyinput name="prevElectricityBill" style="background-color: #ffffff;" type="number" v-model="orderInfo.prevElectricityBill" disabled/>
					</uni-forms-item>
					<uni-forms-item label="上月欠缴电费" name="totalElectricityOweBill">
						<uni-easyinput name="totalElectricityOweBill" style="background-color: #ffffff;" type="number" v-model="orderInfo.totalElectricityOweBill" disabled/>
					</uni-forms-item>
					<uni-forms-item label="上月水表读数" name="prevWater">
						<uni-easyinput name="prevWater" style="background-color: #ffffff;" type="number" v-model="orderInfo.prevWater" disabled/>
					</uni-forms-item>
					<uni-forms-item label="上月水费" name="prevWaterBill">
						<uni-easyinput name="prevWaterBill" style="background-color: #ffffff;" type="number" v-model="orderInfo.prevWaterBill" disabled/>
					</uni-forms-item>
					<uni-forms-item label="上月欠缴水费" name="totalWaterOweBill">
						<uni-easyinput name="totalWaterOweBill" style="background-color: #ffffff;" type="number" v-model="orderInfo.totalWaterOweBill" disabled/>
					</uni-forms-item>
					<uni-forms-item label="上月公共用电" name="prevPublicElectricity">
						<uni-easyinput name="prevPublicElectricity" style="background-color: #ffffff;" type="number" v-model="orderInfo.prevPublicElectricity" disabled/>
					</uni-forms-item>
					<uni-forms-item label="本月公共用电" name="publicElectricity">
						<uni-easyinput name="publicElectricity" style="background-color: #ffffff;" type="number" v-model="orderInfo.publicElectricity" disabled/>
					</uni-forms-item>
					<uni-forms-item label="本月电表读数" name="electricity">
						<uni-easyinput name="electricity" style="background-color: #ffffff;" type="number" v-model="orderInfo.electricity" disabled/>
					</uni-forms-item>
					<uni-forms-item label="公共用电占比(%)" name="publicPercent">
						<uni-easyinput name="publicPercent" style="background-color: #ffffff;" type="number" v-model="orderInfo.publicPercent" @input="publicPercentChange"/>
					</uni-forms-item>
					<uni-forms-item required label="当前用电单价" name="electricityUnitPrice">
						<uni-easyinput name="electricityUnitPrice" style="background-color: #ffffff;" type="number" v-model="orderInfo.electricityUnitPrice" @input="elUnitPriceChange"/>
					</uni-forms-item>
					<uni-forms-item label="本月电费" name="electricityBill">
						<uni-easyinput name="electricityBill" style="background-color: #ffffff;" type="number" v-model="orderInfo.electricityBill" disabled/>
					</uni-forms-item>
					<uni-forms-item label="本月水表读数" name="water">
						<uni-easyinput name="water" style="background-color: #ffffff;" type="number" v-model="orderInfo.water" disabled/>
					</uni-forms-item>
					<uni-forms-item label="当前用水单价" name="waterUnitPrice">
						<uni-easyinput name="waterUnitPrice" style="background-color: #ffffff;" type="number" v-model="orderInfo.waterUnitPrice" @input="waUnitPriceChange"/>
					</uni-forms-item>
					<uni-forms-item label="本月水费" name="waterBill">
						<uni-easyinput name="waterBill" style="background-color: #ffffff;" type="number" v-model="orderInfo.waterBill" disabled/>
					</uni-forms-item>
					<uni-forms-item label="本月状态" name="state">

						<uni-easyinput name="orderInfo.state" style="background-color: #ffffff;" type="text" v-model="orderInfo.state" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="录入月份" name="useDate">
					
						<uni-datetime-picker
							type="date"
							:value="useDate"
							disabled
						/>
					</uni-forms-item>
				</uni-forms>
			</view>
			<view v-if="isHistory" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="open">录入</button>
				</view>
				<view class="right-part">
					<button class="right-button"  @click="back">返回</button>
				</view>
			</view>
			<view v-if="!isHistory" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="open">录入</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="checkHistory">查看历史</button>
				</view>
			</view>
		</view>
		<uni-popup ref="popup" type="dialog">
		    <uni-popup-dialog mode="base" message="成功消息" title="是否同时发起缴费通知？" :duration="2000" :before-close="true" @close="close" @confirm="confirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>		

<script>
	import {
		ONLINE_SERVER_ADDRESS_BASE_2,
		syncGetOrder
	} from "../../../util/network.js"
	import {
		processHistoryList,
		getNowFormatDate
	} from "../../../util/common.js"
	export default{
		data() {
			return {
				orderInfo:{
					'build':'',
					'floor':'',
					'unit':'',
					'date':'',
					'state':'',
					'desc':'',
					'water':'',
					'electricity':'',
					'electricityUnitPrice':'',
					'waterUnitPrice':'',
					'publicElectricity':'',
					'publicPercent':'',
				},
				useDate:'',
				buildId:0,
				processFlag:false,
				recordId: -1,
				status:-1,
				goodList:[],
				itemList:[],
				stateList:['正常','异常'],
				index:0,
				proccessList:[
					{'type':'firstCanvas','commentMsg':'发起申请','time':'2021-01-01 01:01:11'},
					{'type':'middleCanvas','commentMsg':'受理','time':'2020-02-02 02:02:22'},
					{'type':'lastCanvas','commentMsg':'办结','time':'2020-03-03 03:33:33'}
				],
				proccessListDefult:[],
				token:'',
				userId:-1,
				beginFlag:false,
				userRightDetail:'',
				isHistory:false,
			}
		},
		methods: {
			checkWater: function(index) {
				//正则表达试
				let temp = (this.orderInfo.waterUnitPrice.match(/^\d*(\.?\d{0,2})/g)[0]) || null
				//重新赋值给input
				let tempBac = (this.orderInfo.water - this.orderInfo.prevWater) * Number(temp)
				this.orderInfo.waterBill = Math.round(tempBac * 100)/100
				this.$nextTick(() => {
					this.orderInfo.waterUnitPrice= temp
				})
			},
			checkElec: function(index) {
				//正则表达试

			},
			open() {
				if(this.orderInfo.state == '已缴费'){
					uni.showModal({
						content:'本月已缴费，无需录入',
						showCancel:false
					});
					return -1
				}
				// if(!(this.orderInfo.prevWater >= 0 && this.orderInfo.prevElectricity >= 0)){
				// 	uni.showModal({
				// 		content:'工程暂未录入上月水电表读数，无法录入费用',
				// 		showCancel:false
				// 	});
				// 	return -1
				// }
				// if((this.orderInfo.prevWater == null || this.orderInfo.prevElectricity == null)){
				// 	uni.showModal({
				// 		content:'工程暂未录入上月水电表读数，无法录入费用',
				// 		showCancel:false
				// 	});
				// 	return -1
				// }
				if(this.orderInfo.prevMeterCcId == null){
					uni.showModal({
						content:'工程暂未录入上月水电表读数，无法录入费用',
						showCancel:false
					});
					return -1
				}
				if(this.recordId == null || this.recordId < 0){
					uni.showModal({
						content:'工程暂未录入当月水电表读数，无法录入费用',
						showCancel:false
					});
					return -1
				}
				let  newdate=getNowFormatDate().split(' ')[0]
				this.beginFlag = false
				if(this.useDate == newdate){
					this.addOrder()
				}else{
					this.$refs.popup.open()
				}
			},
			/**
			 * 点击取消按钮触发
			 * @param {Object} done
			 */
			close() {
				// TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
				// ...
				this.addOrder()
				this.$refs.popup.close()
			},
			/**
			 * 点击确认按钮触发
			 * @param {Object} done
			 * @param {Object} value
			 */
			confirm(value) {
				this.beginFlag = true
				this.$refs.popup.close()
				this.addOrder()
			},
			bindPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.target.value)
				this.index = e.target.value
				this.status = this.index
				this.orderInfo.state = this.stateList[this.index]
			},
			change(e) {
				this.useDate = e;
				console.log("-change事件:", e);
			},
			publicPercentChange(e){
				//正则表达试
				let temp = (this.orderInfo.publicPercent.match(/^\d*(\.?\d{0,2})/g)[0]) || null
				//重新赋值给input
				temp = temp <= 100 ? temp : 100
				let tempBac = ((this.orderInfo.publicElectricity - this.orderInfo.prevPublicElectricity) * Number(temp)/100 + (this.orderInfo.electricity - this.orderInfo.prevElectricity)) * Number(this.orderInfo.electricityUnitPrice)
				this.orderInfo.electricityBill = Math.round(tempBac * 100)/100
				this.$nextTick(() => {
					this.orderInfo.publicPercent = temp <= 100 ? temp : 100
				})
			},
			
			elUnitPriceChange(e){
				console.log(e)
				let temp = (e.match(/^\d*(\.?\d{0,2})/g)[0]) || null
				//重新赋值给input
				let tempBac = ((this.orderInfo.publicElectricity - this.orderInfo.prevPublicElectricity) * Number(this.orderInfo.publicPercent)/100 + (this.orderInfo.electricity - this.orderInfo.prevElectricity)) * Number(temp)
				this.orderInfo.electricityBill = Math.round(tempBac * 100)/100
				console.log(tempBac)
				this.$nextTick(() => {
					this.orderInfo.electricityUnitPrice= temp
				})
			},

			waUnitPriceChange(e){
			  this.checkWater()
			},
			addOrder(){
				let _this = this
				if(this.orderInfo.publicPercent == null){
					this.orderInfo.publicPercent = 0
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/meter-cc/mod-finance/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						electricityBill:this.orderInfo.electricityBill,
						waterBill:this.orderInfo.waterBill,
						electricityUnitPrice:this.orderInfo.electricityUnitPrice,
						waterUnitPrice:this.orderInfo.waterUnitPrice,
						publicPercent:this.orderInfo.publicPercent,
					},
					method:'POST',
					success: function (res) {
						console.log("提交录入成功",res);
						if(res.data.code == 200){
							if(_this.beginFlag){
								_this.onlinePay()
							}else{
								uni.navigateBack()
							}
						}
					},
					fail: (res) => {
						console.log("提交巡查调用失败")
					}
				})
			},
			onlinePay(){
			    this.itemList = []
			    let itemAllprice = Number(this.orderInfo.waterBill) + Number(this.orderInfo.totalWaterOweBill)
			    itemAllprice = Math.round(itemAllprice * 100)/100
				if(itemAllprice > 0){
					let temp = {"name":"水费","desc":"每月及历史用水","curPrice":this.orderInfo.waterBill,"lastPrice":this.orderInfo.totalWaterOweBill,"lateFee":0,"allPrice":itemAllprice}
					this.itemList.push(temp)
				}
			    let itemAllprice1 = Number(this.orderInfo.electricityBill) + Number(this.orderInfo.totalElectricityOweBill)
			    itemAllprice1 = Math.round(itemAllprice1 * 100)/100
			    let temp1 = {"name":"电费","desc":"每月及历史用电","curPrice":this.orderInfo.electricityBill,"lastPrice":this.orderInfo.totalElectricityOweBill,"lateFee":0,"allPrice":itemAllprice1}
			    this.itemList.push(temp1)
				let allPrice = itemAllprice1 + itemAllprice
				if(allPrice <= 0){
					uni.showModal({
						content:'如果水电费总额为0，则无需发起缴费通知',
						showCancel:false
					});
					return -1
				}
				this.endDate = this.useDate
				console.log(this.endDate)
				let msg = ''
				if(this.userRightDetail.exchangeRent.primeAuth == 5){
					msg = "财务主管发起缴费通知"
				}else{
					msg = "财务专员发起缴费通知"
				}
				
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/payment-notice/add`,
					header: {
						'Authorization': this.token,
					},
					data: {
						itemList:JSON.stringify(this.itemList),
						leaseTime:this.endDate + " 23:59:59",
						payType:2,
						price:Number(allPrice),
						userId:parseInt(this.userId),
						commentMsg: msg,                      //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("发起缴费成功",res);
						if(res.data.code == 200){
							uni.showModal({
								content:'已发送水电费缴费通知',
								showCancel:false
							});
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("发起缴费调用失败")
					}
				})
			},
			checkHistory(){
				uni.navigateTo({
					url:'../history/historySelf?id=' + this.userId
				})
			},
			back(){
				uni.navigateBack()
			}
		},
		onLoad(option) {
			//传入单号
			this.token = uni.getStorageSync('token')
			let json = JSON.parse(option.data)
			this.recordId = json.orderNum == null ? null : parseInt(json.orderNum)
			this.orderInfo.prevMeterCcId = json.prevMeterCcId
			this.orderInfo.build = json.buildName
			this.orderInfo.floor = json.houseFloor
			this.orderInfo.unit = json.houseNumber
			this.orderInfo.water = json.water
			this.orderInfo.electricity = json.electricity
			this.orderInfo.state = json.state
			this.orderInfo.waterBill = json.waterBill
			this.orderInfo.electricityBill = json.electricityBill
			this.orderInfo.publicElectricity = json.publicElectricity
			this.orderInfo.prevPublicElectricity = json.prevPublicElectricity
			this.orderInfo.prevWater = json.prevWater
			this.orderInfo.prevWaterBill = json.prevWaterBill
			this.orderInfo.prevElectricity = json.prevElectricity
			this.orderInfo.prevElectricityBill = json.prevElectricityBill
			this.orderInfo.totalElectricityOweBill = json.totalElectricityOweBill
			this.orderInfo.totalWaterOweBill = json.totalWaterOweBill
			this.orderInfo.electricityUnitPrice = json.electricityUnitPrice
			this.orderInfo.waterUnitPrice = json.waterUnitPrice
			this.orderInfo.publicPercent = json.publicPercent
			this.orderInfo.useDate = json.useDate.replace(/-/g, '/')
			// if((this.orderInfo.prevWater == null || this.orderInfo.prevElectricity == null) || (!(this.orderInfo.prevWater >= 0 && this.orderInfo.prevElectricity >= 0))){
			// 	uni.showModal({
			// 		content:'工程暂未录入上月水电表读数',
			// 		showCancel:false
			// 	});
			// }
			this.useDate = json.useDate + "-01"
			console.log(this.useDate)
			this.buildId = parseInt(json.buildId)
			this.userId = json.userId
			this.userRightDetail = uni.getStorageSync("userRight")
			console.log("this.orderInfo",this.orderInfo)
			if(json.isHistory != null && json.isHistory != ''){
				this.isHistory = true
			}
			if(this.orderInfo.prevMeterCcId == null || this.recordId == null || this.recordId < 0 || this.orderInfo.state == '已缴费'){
				console.log('not cal')
			}else{
				let tempBac = ((this.orderInfo.publicElectricity - this.orderInfo.prevPublicElectricity) * Number(this.orderInfo.publicPercent)/100 + (this.orderInfo.electricity - this.orderInfo.prevElectricity)) * Number(this.orderInfo.electricityUnitPrice)
				this.orderInfo.electricityBill = Math.round(tempBac * 100)/100
				//重新赋值给input
				tempBac = (this.orderInfo.water - this.orderInfo.prevWater) * Number(this.orderInfo.waterUnitPrice)
				this.orderInfo.waterBill = Math.round(tempBac * 100)/100
			}
		},

		// onShow() {
		// 	if((this.orderInfo.prevWater == null || this.orderInfo.prevElectricity == null) || (!(this.orderInfo.prevWater >= 0 && this.orderInfo.prevElectricity >= 0))){
		// 		uni.showModal({
		// 			content:'工程暂未录入上月水电表读数',
		// 			showCancel:false
		// 		});
		// 	}
		// }
	}
</script>

<style>
	page{
		background-color: #ffffff
	}
	.record-id{
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}
	.state-bar{
		display: flex;
		align-items: center;
		color: #FFFFFF;
		background-color: #DD524D;
		width: 260rpx;
		justify-content: center;
		margin-left: auto;
		margin-right: 50rpx;
		font-size: 30rpx;
		border-radius: 50rpx;
		height: 50rpx;
	}
	.state-msg{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.item-table{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.mix-button{
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 50rpx;
	}
	.left-part{
		float: right;
	}
	.right-part{
		float: left;
	}
	.left-button{
		background-color: #FF0000;
		border-radius: 50rpx 0 0 50rpx;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.right-button{
		background-color: #0000FF;
		border-radius: 0 50rpx 50rpx 0;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.in-center{
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.add-button {
		border-width: 0px;
		align-items: center;
		justify-content: center;
		margin: 30rpx 0 40rpx 250rpx;
		height: 50rpx;
		width: 250rpx;
		display: flex;
		color: #22B242;
	}
</style>
